<?php

namespace app\common\middleware;

use helper\Auth;

class App
{
    public function handle($request, \Closure $next)
    {
        $auth = new Auth();
        $auth->setToken($request->header('authorization', ''));
        // 预检OPTIONS请求,服务器响应是200（ok），然后它跟进其他请求
        if ($request->isOptions()) {
            return json(['code' => 204, 'msg' => 'No Content'], 204);
        }
        // 验证token信息
        if (!$auth->tokenVerify()){
            return json(['code' => 10001, 'msg' => 'Authorization failed'], 401);
        }
        // 获取token信息
        $payload = $auth->getPayload();

        // 传递数据
        $request->user = (object) ['id' => $payload['sub']];

        return $next($request);
    }
}